/**
 * 
 */
package com.tomagency.cyberlab.client.ui;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.Cell;
import com.google.web.bindery.requestfactory.shared.Receiver;

import com.tomagency.cyberlab.client.CssGlobalStyleNames;
import com.tomagency.cyberlab.client.RpcServiceProvider;
import com.tomagency.cyberlab.client.events.BelegEvent;
import com.tomagency.cyberlab.client.ui.ObjectListenView.CellRenderer;
import com.tomagency.cyberlab.client.ui.ObjectListenView.RenderType;
import com.tomagency.cyberlab.client.ui.ObjectListenView.RowRenderer;


import de.gammadata.gwt.proxy.PersistenceBeanListProxy;

/**
 * @author gfr
 *
 */
public class ObjectListenViewImpl extends Composite implements ObjectListenView {
	
	
	@UiTemplate("ObjectListenView.ui.xml")
	interface ObjectListenViewUiBinder extends UiBinder<Widget, ObjectListenViewImpl> {}
	
	private static ObjectListenViewUiBinder uiBinder = GWT
	.create(ObjectListenViewUiBinder.class);

	
	/*
	 * UI Felder die mit uiBinder gebunden werden
	 */
	@UiField(provided=true)
	FlexTable objectTabelle;
	@UiField
	Button button;
	@UiField
	Button searchButton;
	@UiField
	TextBox searchTxt;
	@UiField
	Label errorLabel;
	@UiField
	Label header;
	
	private Presenter presenter;
	private ObjectEventHandler objectEventHandler;
	private RowRenderer rowRenderer;
	private List objectList;
	private int rowCount=0;
	private String objektBezeichnung;

	
	public ObjectListenViewImpl(String objektBez,RowRenderer rowRenderer){
		objektBezeichnung=objektBez;
		objectTabelle = new FlexTable();
		objectTabelle.addStyleName(CssGlobalStyleNames.LISTE);
		objectTabelle.addClickHandler(new TabClickHandler());
		this.rowRenderer=rowRenderer;
		initWidget(uiBinder.createAndBindUi(this));
		SuchHandler sh = new SuchHandler();
		searchButton.addClickHandler(sh);
		searchTxt.addKeyUpHandler(sh);
		render();		
	}
	
	@Override
	public void render() {
		
		objectTabelle.removeAllRows();
		button.setText("Alle anzeigen");
		errorLabel.setText("");
		searchTxt.setText("");
		searchButton.setText(objektBezeichnung+" suchen");
		searchTxt.setFocus(true);
		searchTxt.selectAll();
		header.setText(objektBezeichnung+ " Liste");
		
	}

	@Override
	public void renderObjectList(int startObjectNr, int anzahlObjekte,int startRow,RenderType renderType) {
		List<CellRenderer> cellRendererList = this.getRowRenderer().getCellRendererList(renderType);
		
		if (objectList!=null && objectList.size()>startObjectNr && cellRendererList!=null ){
			
			int lastObjectNr = (startObjectNr+anzahlObjekte>objectList.size()) ? objectList.size():startObjectNr+anzahlObjekte;			
			int row = objectTabelle.getRowCount()>startRow ? startRow : objectTabelle.getRowCount();
			
			for (int i = startObjectNr;i<lastObjectNr;i++){
				
				if (objectTabelle!=null
//						&&objectTabelle.getRowCount()>0
						&&objectTabelle.getRowCount()>row
						&&objectTabelle.getCellCount(row)>0){
					objectTabelle.removeCells(row, 0, objectTabelle.getCellCount(row));
				}
				int col=0;
				
				for (CellRenderer cr : cellRendererList){
					Widget cw=cr.getColumnWidget(RowType.STANDARD, objectEventHandler, objectList.get(i));
					int colspan = cr.getColSpan();
					if (cw!=null){
						
						if (colspan>1){
							objectTabelle.getFlexCellFormatter().setColSpan(row, col, colspan);
						}
						
						objectTabelle.setWidget(row, col, cw);
					}
					col++;					
				}
				row++;
			}
			
			rowCount = row;
			
		}
		
	}
	
	@Override
	public void clearListenTabelle() {
		objectTabelle.removeAllRows();
		
	}

	
	@UiHandler("button")
	void onClick(ClickEvent e) {
		searchTxt.setText("");
		presenter.onShowAllClicked();
	}
	
	class SuchHandler implements ClickHandler, KeyUpHandler {
		/**
		 * Fired when the user clicks on the sendButton.
		 */
		public void onClick(ClickEvent event) {
			presenter.onSearchClicked(searchTxt.getText());
//			sucheBelege(searchTxt.getText());
		}

		/**
		 * Fired when the user types in the nameField.
		 */
		public void onKeyUp(KeyUpEvent event) {
			if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
				presenter.onSearchClicked(searchTxt.getText());
//				sucheBelege(searchTxt.getText());
			}
			else if(searchTxt.getText().length()>3){
				presenter.onSearchClicked(searchTxt.getText());
//				sucheBelege(searchTxt.getText());
			}
		}
	}


	/**
	 * @return the objektBezeichnung
	 */
	public String getObjektBezeichnung() {
		return objektBezeichnung;
	}

	/**
	 * @param objektBezeichnung the objektBezeichnung to set
	 */
	public void setObjektBezeichnung(String objektBezeichnung) {
		this.objektBezeichnung = objektBezeichnung;
	}

	@Override
	public List getObjectList(){
		return objectList;
	}

	@Override
	public void setObjectList(List dataList) {
		this.objectList=dataList;
		
	}
	@Override
	public void setMessage(String msg) {
		errorLabel.setText(msg);
		
	}
	
	@Override
	public Presenter getPresenter() {
		return presenter;
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter=presenter;		
	}

	/**
	 * @return the objectEventHandler
	 */
	public ObjectEventHandler getObjectEventHandler() {
		return objectEventHandler;
	}

	/**
	 * @param objectEventHandler the objectEventHandler to set
	 */
	public void setObjectEventHandler(ObjectEventHandler objectEventHandler) {
		this.objectEventHandler = objectEventHandler;
	}

	/**
	 * @return the rowRenderer
	 */
	public RowRenderer getRowRenderer() {
		return rowRenderer;
	}

	/**
	 * @param rowRenderer the rowRenderer to set
	 */
	public void setRowRenderer(RowRenderer rowRenderer) {
		this.rowRenderer = rowRenderer;
	}

	@Override
	public int getAbsoluteBottom() {		
		return this.getElement().getAbsoluteBottom();
	}

	@Override
	public int getAbsoluteRight() {
		return this.getElement().getAbsoluteRight();
	}



	@Override
	public int getRowCount() {
		return rowCount;
	}
	
	private class TabClickHandler implements ClickHandler{

		@Override
		public void onClick(ClickEvent event) {
		
			Object sender = event.getSource();
			
			if (sender == objectTabelle) {
			      // Select the row that was clicked (-1 to account for header row).
			      Cell cell = objectTabelle.getCellForEvent(event);
			      if (cell==null)
			    	  return;
			      event.stopPropagation();
			      int selectedRow = cell.getRowIndex();
			      if (objectList!=null&&objectList.size()>selectedRow)
			    	  if (objectList.get(selectedRow) instanceof PersistenceBeanListProxy){
			  			int id=((PersistenceBeanListProxy)objectList.get(selectedRow)).getId();
			  			presenter.onObjectClicked(selectedRow, id);
			  		}
			    	  

			}
			else{
				 Window.alert("Click auf objekt: "+sender);
			}
			
		}
	}



}
